package wypozyczalnia.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import wypozyczalnia.domain.User;
import wypozyczalnia.forms.SettingsForm;
import wypozyczalnia.service.UserService;

@Controller
@RequestMapping(value = "/user/*")
public class ProfileController {

	private final Logger logger = Logger.getLogger(ProfileController.class);
	@Autowired
	UserService userService;

	@RequestMapping(value = "start.do")
	public String startPage() {

		logger.info("Udalo sie zalogowac");
		System.out.println("jestem w starcie udalo sie logowanie!");
		return "start";
	}

	@RequestMapping(value = "/settings.do", method = RequestMethod.GET)
	public String setting(HttpSession session, HttpServletResponse response,
			HttpServletRequest request, Model model, SettingsForm settingsForm) {

		User user = userService.getUserByUsername((String) session
				.getAttribute("currentUserName"));
		model.addAttribute("oldPassword", user.getPassword());
		settingsForm.setEmail(user.getEmail());
		settingsForm.setPhone(user.getPhone());

		return "settings";

	}

	@RequestMapping(value = "changeSettings.do", method = RequestMethod.POST)
	public String changeSetting(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			Model model, @ModelAttribute SettingsForm settingsForm) {
		String oldPass = settingsForm.getOldPass();
		String pass1 = settingsForm.getPass1();
		String pass2 = settingsForm.getPass2();
		String email = settingsForm.getEmail();
		Integer phone = settingsForm.getPhone();

		User user = userService.getUserByUsername((String) session
				.getAttribute("currentUserName"));
		
		if (email != null && email != "") {
			user.setEmail(email);
		}
		if (phone != null) {
			user.setPhone(phone);
		}
		if (oldPass.equals(user.getPassword()) && pass1 != null && pass1 != ""
				&& pass1.equals(pass2)) {
			user.setPassword(pass1);
		}
		userService.update(user);
		return "start";

	}
}